<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\controller\Admin;
use think\facade\Cache;
use think\facade\Session;
use think\Request;

class User extends Admin
{
    protected $popup_size = ['width'=>'500px','height'=>'600px'];
    protected $middleware = [
        \app\middleware\AdminLoginCheck::class => ['except' => ['login', 'admin_login']]
    ];
    public function initialize()
    {
        $this->menu_input = [
                'all' => [

                ],
                'add' => [
                    ['type' => 'text', 'name' => '昵称', 'key' => 'name','verify'=>'nickname'],
                    ['type' => 'text', 'name' => '账号', 'key' => 'username','verify'=>'required'],
                    ['type' => 'password', 'name' => '密码', 'key' => 'password','verify'=>'required'],
                    ['type' => 'y_image', 'name' => '头像', 'key' => 'image','verify'=>'required'],
                    ['type' => 'text', 'name' => '电话', 'key' => 'tel'],
                    ['type' => 'text', 'name' => '邮箱', 'key' => 'email'],
                    ['type' => 'radio', 'name' => '性别', 'key' => 'sex',
                        'data'=>['1'=>'男','2'=>'女'],
                        'required'=>1
                    ],

                ],
                'upload' => [
                    ['type' => 'text', 'name' => '昵称', 'key' => 'name'],
                    ['type' => 'password', 'name' => '新密码', 'key' => 'password'],
                    ['type' => 'y_image', 'name' => '头像', 'key' => 'image'],
                    ['type' => 'text', 'name' => '电话', 'key' => 'tel'],
                    ['type' => 'text', 'name' => '邮箱', 'key' => 'email'],
                    ['type' => 'radio', 'name' => '性别', 'key' => 'sex',
                        'data'=>['1'=>'男','2'=>'女']
                    ],

                ],
        ];
        parent::initialize(); // TODO: Change the autogenerated stub
    }
    public function table_mage(&$data = [])
    {
        $data = [
            ['field' => 'name', 'title' => '昵称'],
            ['field' => 'username', 'title' => '账号'],
            ['field' => 'image', 'title' => '头像', 'templet' => '#list_image'],
            ['field' => 'last_ip', 'title' => '最后登录ID'],
            ['field' => 'create_time', 'title' => '添加时间'],
            ['field' => 'update_time', 'title' => '修改时间'],
            ['title' => '操作', 'templet' => '#list_setting','width'=>'15%']
        ];
        return parent::table_mage($data); // TODO: Change the autogenerated stub
    }
    public function index_handle(&$data)
    {
//        foreach ($data['data'] as &$v){
//            $v['image'] = $v['file_id_image']['url'];
//        }
        return parent::index_handle($data); // TODO: Change the autogenerated stub
    }
    //我的资料-页面
    public function info()
    {
        $data = $this->model->where('id',input('id'))->with('fileIdImage')->find()->toArray();
        $this->assign('data',$data);
        return view();
    }
    //身份添加-页面
    public function usergroup()
    {
        $Group_model = app('app\admin\model\Group');
        $Group_data = $Group_model->select()->toArray();
        $UserGroup_model = app('app\admin\model\UserGroup');
        $UserGroup_data = $UserGroup_model->where('user_id',input('id'))->select();
        if(!empty($UserGroup_data) && !empty($UserGroup_data->toArray())){
            $UserGroup_data = $UserGroup_data->toArray();
            foreach ($Group_data as $k=>$v){
                foreach ($UserGroup_data as $kk=>$vv){
                    if($v['id'] == $vv['group_id']){
                        $Group_data[$k]['checked'] = true;
                    }
                }
            }
        }
        $this->assign(['group'=>$Group_data,'id'=>input('id')]);
        return view();
    }
    //身份添加-接口
    public function user_group_ajax()
    {
        if(request()->isAjax())
        {
            $post = input('post.');
            $UserGroup_model = app('app\admin\model\UserGroup');
            $arr = [];
            $UserGroup_model->where('user_id','=',$post['id'])->delete();
            if(!empty($post['group_id'])){
                foreach($post['group_id'] as $v)
                {
                    $arr[] = ['user_id'=>$post['id'],'group_id'=>$v];
                }
                $UserGroup_model->saveAll($arr);
            }
            return datasuccess($arr);
        }
    }
    //添加-数据接口
    public function add_ajax()
    {
        if(request()->isAjax()){
            $post = array_filter(input('post.'));
            if($post){
                $user = $this->model->where('username','=',$post['username'])->find();
                if(!empty($user)){
                    return msgerror('该账户已存在添加失败');
                }
                $c = input('c');
                    unset($post['c']);
                $this->model->save($post);
                if(!empty($c)){
                    $data = [];
                    foreach ($c as $k=>$v){
                        $data[] = ['user_id'=>$this->model->id,'township_id'=>$v];
                    }
                    app('app\admin\model\UserTow')->saveAll($data);
                }
            }
            return datasuccess($post);
        }
    }
    //登录-页面
    public function login()
    {
        return view();
    }
    //密码修改
    public function password()
    {
        if (request()->isAjax())
        {
            $post = array_filter(input('post.'));
            if(!isset($post['oldPassword']) || !isset($post['password'])) return msgerror('参数缺失');
            if(jm($post['oldPassword']) == Session::get('login')['password']){
                $this->model::update(['id'=>Session::get('login')['id'],'password'=>$post['password']]);
            }else{
                return msgerror('密码错误，修改失败');
            }
            return datasuccess();
        }
        return view();
    }
    //登录验证
    public function admin_login(\app\admin\model\User $usermodel)
    {
        if (request()->isAjax()) {
            $param = request()->param();
            $validate = app('\app\admin\validate\User');
            if ($validate->check($param)) {
                $param['password'] = jm($param['password']);
                $user = $usermodel->where([
                    ['username', '=', $param['username']],
                    ['password', '=', $param['password']]
                ])->with('usergroup.group.authoritygroup.authority')->find();
                if (!empty($user)) {
                    $user = $user->toArray();
                    $url = [];
                    if (!empty($user['usergroup'])) {
                        foreach($user['usergroup'] as $k=>$v){
                            if(!empty($v['group']) && !empty($v['group']['authoritygroup'])){
                                foreach ($v['group']['authoritygroup'] as $kk=>$vv){
                                    if(!empty($vv['authority'])){
                                        $url[] = $vv['authority'];
                                    }
                                }
                            }
                        }
                        if(!empty($url)){
                            $url = array_unique($url, SORT_REGULAR);
                            foreach ($url as $v){
                                $url_id[] = $v['id'];
                            }
                            $url_id = implode(',',$url_id);
                            $Authority_model = app('\app\admin\model\Authority');
                            $url = $Authority_model->order('id asc')->where('id','in',$url_id)->select()->toArray();
                            $url = getTree($url,0);
                            Cache::set('admin_menu'.$user['id'],$url);
                            if($url[0]['module'] != 'admin' || $url[0]['controller'] != 'index' || $url[0]['method'] != 'index') return msgerror('没有后端面板权限');
                            Session::set('login', $user);
                            $Browser = userBrowser();
                            $Browser_model = app('app\admin\model\Browser');
                            $Browser_data = $Browser_model->where('name','=',$Browser)->find();
                            if(!empty($Browser_data) && !empty($Browser_data->toArray())){
                                $Browser_model->where('id', $Browser_data->id)
                                    ->inc('num')
                                    ->update();
                            }else{
                                $Browser_model->save([
                                    'name'=>$Browser,
                                    'num'=>1
                                ]);
                            }
                            return datasuccess($user);
                        }
                    }
                    return msgerror('没有后台权限');
                }
                return msgerror('账号或密码错误');
            } else {
                return msgerror($validate->getError());
            }
        }
    }
    //退出登录
    public function exit()
    {
        Session::delete('login');
        Session::clear();
        return redirect('login');
    }
    //添加-页面
    public function add()
    {
        return view();
    }
    //编辑-页面
    public function upload()
    {
        $id = input('id');
        $data = $this->model->where('id', $id)->with($this->with)->find()->toArray();
        $this->assign('data', $data);
        return view();
    }
    //编辑-数据接口
    public function upload_ajax()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if ($post) {

                $this->model::update($post);
            }
            return datasuccess($post);
        }
    }
    //刷新数据
    public function refresh()
    {
        $user = $this->model->where('id','=',Session::get('login')['id'])
            ->with('usergroup.group.authoritygroup.authority')->find();
        if (!empty($user)) {
            $user = $user->toArray();
            $url = [];
            if (!empty($user['usergroup'])) {
                foreach($user['usergroup'] as $k=>$v){
                    if(!empty($v['group']) && !empty($v['group']['authoritygroup'])){
                        foreach ($v['group']['authoritygroup'] as $kk=>$vv){
                            if(!empty($vv['authority'])){
                                $url[] = $vv['authority'];
                            }
                        }
                    }
                }
                if(!empty($url)){
                    $url = array_unique($url, SORT_REGULAR);
                    foreach ($url as $v){
                        $url_id[] = $v['id'];
                    }
                    $url_id = implode(',',$url_id);
                    $Authority_model = app('\app\admin\model\Authority');
                    $url = $Authority_model->order('id asc')->where('id','in',$url_id)->select()->toArray();
                    $url = getTree($url,0);
                    Cache::set('admin_menu'.$user['id'],$url);
                    if($url[0]['module'] != 'admin' || $url[0]['controller'] != 'index' || $url[0]['method'] != 'index') return msgerror('没有后端面板权限');
                    Session::set('login', $user);
                    return redirect('/admin/index/index');
                }
            }
        }
    }
}
